package com.mgg.message.service.sms.impl;

import java.util.HashMap;
import java.util.Map;

import com.mgg.common.enums.SmsTypeEnum;
import com.mgg.common.vo.UserVO;
import com.mgg.common.dao.DaoSupport;
import com.mgg.message.service.sms.SmsService;
import com.mgg.message.sms.SmsSender;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.druid.support.json.JSONUtils;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;

@Service("smsService")
public class SmsServiceImpl implements SmsService {
	
	Logger log = LoggerFactory.getLogger(getClass());
	
	@Autowired
	private DaoSupport dao;
	
	@Autowired
    private SmsSender smsSender;
	
	@Override
	public Map<String, String> getSmsConfigByType(Integer smsType, Integer subType) throws Exception {
		Map<String,Integer> queryMap = new HashMap<>();
		queryMap.put("smsType", smsType);
		queryMap.put("subType", subType);
		return dao.findForObject("SmsMapper.getSmsConfigByType", queryMap);
	}

	@Override
	public void insertSmsSendLog(String smsId, String mobile, String content, String remark, String status)
			throws Exception {
		Map<String,String> map = new HashMap<>();
		map.put("smsId", smsId);
		map.put("mobile", mobile);
		map.put("content", content);
		map.put("remark", remark);
		map.put("status", status);
		dao.save("SmsMapper.insertSmsLog", map);
	}

	@Override
	public UserVO getUserById(String userId) throws Exception {
		return (UserVO) dao.findForObject("SmsMapper.findUserById", userId);
	}
	
	/**
	 * 短信发送
	 * @param smsTypeEnum
	 * @param mobile
	 * @param paramMap
	 * @throws Exception
	 */
	@Override
	public void send(SmsTypeEnum smsTypeEnum, String mobile, Map<String,String> paramMap) {
		try {
			String param = JSONUtils.toJSONString(paramMap);
			send(smsTypeEnum.getSmsType(), smsTypeEnum.getSubType(), mobile, param);			
		} catch(Exception e) {
			log.error("短信发送失败，exception = {}",e);
		}
	}

	/**
	 * 短信发送
	 * @param smsType
	 * @param subType
	 * @param mobile
	 * @param param
	 * @throws Exception
	 */
	@Override
	public void send(Integer smsType, Integer subType, String mobile, String param) throws Exception {
		Map<String,String> configMap = getSmsConfigByType(smsType,subType);
		String signName = configMap.get("sign_name");
		String templateCode = configMap.get("template_code");
		
		SendSmsResponse sendSmsResponse = smsSender.send(mobile, signName, templateCode, param);	
		String smsId = configMap.get("id");	
		if (sendSmsResponse.getCode() != null && sendSmsResponse.getCode().equals("OK")) {
			// 请求成功
			insertSmsSendLog(smsId,mobile,param,"","100");
		} else {
			// 请求失败
			String remark = "code: " + sendSmsResponse.getCode() + ", message: " + sendSmsResponse.getMessage();
			insertSmsSendLog(smsId,mobile,param,remark,"99");
		}
	}
}
